<template>
  <view class="page">
    <view class="container">

      <!-- 🏥 医院信息部分 -->
      <view class="hospital-info">
        <!-- 医院头像 -->
        <image class="hospital-avatar" src="/static/hospital.png"/>

        <!-- 医院名称和科室 -->
        <view class="hospital-details">
          <text class="hospital-name">{{ hospitalInfo.name }}</text>
          <text class="hospital-department">{{ hospitalInfo.department }}</text>
        </view>
      </view>

      <!-- 分割线 -->
      <view class="divider"></view>

      <!-- 👨‍⚕️ 医生信息部分 -->
      <view class="doctor-info">
        <!-- 就诊日期 -->
        <view class="info-row">
          <text class="info-label">就诊日期：</text>
          <text>{{ doctorInfo.date }} {{ doctorInfo.week }} {{ doctorInfo.time }}</text>
        </view>

        <!-- 专家职称 -->
        <view class="info-row">
          <text class="info-label">专家职称：</text>
          <text>{{ doctorInfo.name }} {{ doctorInfo.title }}</text>
        </view>

        <!-- 擅长领域 -->
        <view class="info-row">
          <text class="info-label">擅长领域：</text>
        </view>
        <view class="doctor-speciality">
          <text>{{ doctorInfo.introduction }}</text>
        </view>
      </view>

      <!-- 分割线 -->
      <view class="divider"></view>


      <!-- 🆕 新增代码开始：就诊信息 -->
      <view class="section-title">就诊信息</view>

      <!-- 选择就诊人和管理按钮 -->
      <view class="select-row">
        <text class="select-title">请选择就诊人：</text>
        <text class="manage-text" @click="navigateToPatientManager">就诊人管理</text>
      </view>

<!--       就诊人列表-->
<!--            <view class="patient-list">-->
<!--              <view-->
<!--                  v-for="(patient, index) in patients"-->
<!--                  :key="index"-->
<!--                  class="patient-item"-->
<!--                  :class="selectedPatientId === patient.id ? 'selected' : ''"-->
<!--                  @click="selectPatient(patient.id)"-->
<!--              >-->
<!--                <view class="check-icon">-->
<!--                  <text v-if="selectedPatientId === patient.id">✔️</text>-->
<!--                </view>-->
<!--                <view class="patient-info">-->
<!--                  <text class="patient-name">{{ patient.name }}</text>-->
<!--                  <text class="patient-phone">{{ maskPhone(patient.phone) }}</text>-->
<!--                </view>-->
<!--              </view>-->
<!--            </view>-->

      <!-- 就诊人选择下拉框 -->
<!--      <view class="patient-select">-->
<!--        <picker @change="onPatientChange" :value="selectedPatientIndex" :range="patients" range-key="name">-->
<!--          <view class="picker-box">-->
<!--            <text>{{ selectedPatientName || '请选择就诊人' }}</text>-->
<!--          </view>-->
<!--        </picker>-->
<!--      </view>-->


      <!-- 就诊人列表 -->
      <view class="patient-list">
        <view
            v-for="(patient, index) in patients"
            :key="patient"
            class="patient-item"
            :class="selectedPatientId === patient ? 'selected' : ''"
            @click="selectPatient(patient)"
        >
          <view class="check-icon">
            <text v-if="selectedPatientId === patient">✔️</text>
          </view>
          <view class="patient-info">
            <text class="patient-name">{{ patient.name }}</text>
            <text class="patient-phone">{{ maskPhone(patient.phone) }}</text>
          </view>
        </view>
      </view>



      <!-- 🆕 新增代码结束 -->
      <!-- 🆕 新增代码开始：付款部分 -->
      <view class="payment-section">
        <!-- 在线支付 -->
        <view class="payment-row">
          <text class="payment-title">在线支付：</text>
          <text class="payment-amount">￥{{ paymentInfo.amount }}</text>
        </view>

        <!-- 退款规则 -->
        <view class="refund-section">
          <view class="refund-title">退款规则：</view>
          <view class="refund-rule" v-for="(rule, index) in paymentInfo.refundRules" :key="index">
            {{ index + 1 }}. {{ rule }}
          </view>
        </view>

        <!-- 立即预约按钮 -->
        <button class="confirm-btn" @click="navigateToRecords">立即预约</button>
      </view>
      <!-- 🆕 新增代码结束 -->
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {

      departmentId: 0,
      doctorId: 0,
      hospitalId: 0,
      selectId:0,
      // 医院信息
      hospitalInfo: {
        name: '',
        department: '',
      },
      // 医生信息
      doctorInfo: {},
      selectedPatientId: null, // 当前选中的就诊人ID
      patients: [],
      // 正确初始化 paymentInfo
      paymentInfo: {
        amount: 500,
        refundRules: [
          '就诊日前一日23:59:59前，取消预约全额退款。',
          '就诊日当天08:00后不予退款。',
          '爽约、不可退款。',
        ],
      },

      selectedPatientIndex: 0, // 选择的下标
      selectedPatientName: '', // 选择的患者姓名

    };
  },


  methods: {

    // 处理选择患者
    onPatientChange(e) {
      this.selectedPatientIndex = e.detail.value;
      const selectedPatient = this.patients[this.selectedPatientIndex];

      if (selectedPatient) {
        this.selectedPatientId = selectedPatient.id;
        console.log("就诊人id:"+this.selectedPatientId)
        this.selectedPatientName = selectedPatient.name;
        console.log("已选择就诊人ID:", this.selectedPatientId);
      }
    },

    // 🆕 选择就诊人
    selectPatient(patientId) {
      if (this.selectedPatientId === patientId) {
        // 如果点击的是当前已选中的就诊人，则取消选择
        this.selectedPatientId = null;
        this.selectId = 0
      } else {
        // 否则，选中新的就诊人
        this.selectedPatientId = patientId;
        this.selectId = patientId.id
      }
    },
    // 🆕 手机号脱敏处理
    maskPhone(phone) {
      return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
    },
    // 🆕 跳转到就诊人管理页面
    navigateToPatientManager() {
      uni.navigateTo({
        url: `/pages/registrations/patient-manager/patient-manager`,
      });
    },


    // 立即预约并发起支付
    async navigateToRecords() {
      // 获取当前日期的下一天
      const getTomorrowDate = () => {
        const today = new Date();
        today.setDate(today.getDate() + 1);  // 设置为下一天
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;  // 格式为 yyyy-MM-dd
      };
      try {
        // 构建支付请求参数
        const requestData = {
          userId: uni.getStorageSync('userInfo').id,           // 从用户信息中获取
          patientId: this.selectId,  // 当前选择的患者ID
          hospitalId: this.hospitalId, // 选择的医院ID
          departmentId: this.departmentId, // 选择的科室ID
          doctorId: this.doctorId,    // 选择的医生ID
          packagePrice: 500,   // 选择的价格
          date: this.selectedDate || getTomorrowDate(),  // 如果未选择日期，默认为当前日期的下一天// 预约的日期
        };

        console.log("前端数据：",requestData)

        // 调用后端支付接口
        const response = await uni.request({
          url: 'http://localhost:8080/app/Registration/pay',
          method: 'POST',
          data: requestData,
          header: {
            'Content-Type': 'application/json'
          },
          success: (res) => {
            console.log('支付请求成功，返回数据:', res);
            if (res.statusCode === 200 && res.data) {
              // 解析并提交支付宝表单
              this.handlePayForm(res.data);
            } else {
              uni.showToast({
                title: '支付请求失败，状态码: ' + res.statusCode,
                icon: 'none',
                duration: 2000
              });
            }
          },
          fail: (err) => {
            console.log('支付请求失败:', err);
            uni.showToast({
              title: '网络错误，请稍后重试',
              icon: 'none',
              duration: 2000
            });
          },
          complete: () => {
            console.log('支付请求完成');
          }
        });

        // 检查支付接口是否成功
      //   if (response.statusCode === 200 && response.data) {
      //     // 返回的是支付宝的支付表单，插入页面自动提交
      //     this.invokeAliPay(response.data);
      //   } else {
      //     uni.showToast({
      //       title: '支付失败，请重试',
      //       icon: 'none'
      //     });
      //   }
      //
      } catch (error) {
        console.error('支付请求失败:', error);
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    },
    // 处理支付宝支付表单并跳转
    handlePayForm(formData) {
      // 动态创建一个临时的 div 元素来解析表单
      const tempDiv = document.createElement('div');
      tempDiv.innerHTML = formData;

      // 获取表单元素
      const form = tempDiv.querySelector('form');
      if (form) {
        // 将表单添加到页面
        document.body.appendChild(form);
        // 手动提交表单，跳转到支付宝支付页面
        form.submit();
      } else {
        uni.showToast({
          title: '支付表单解析失败',
          icon: 'none',
          duration: 2000
        });
      }
    },

    // // 处理支付宝支付表单
    // invokeAliPay(payForm) {
    //   const div = document.createElement('div');
    //   div.innerHTML = payForm;
    //   document.body.appendChild(div);
    //   document.forms[0].submit();
    // },
    onLoad(options) {
      this.doctorId = options.doctorId || '未知';
      this.departmentId = options.departmentId;
      this.hospitalId = options.hospitalId;
      console.log("科室id" + this.departmentId)
      console.log("医院id" + this.hospitalId)
      console.log("医生id" + this.doctorId)

    },
    getDoctorInfo() {
      uni.request({
        url: 'http://localhost:8080/app/registration/listDoctorsById/' + this.doctorId,
        method: 'GET',
        success: result => {
          console.log("test", result.data)
          if (result.statusCode == 200) {
            this.doctorInfo = result.data
            this.hospitalInfo = result.data
          }
        }
      })
    },

    getPatients() {
      var userInfo = uni.getStorageSync('userInfo');
      console.log(userInfo.id)
      uni.request({
        url: 'http://localhost:8080/app/registration/listByUserId/' + userInfo.id,
        method: 'GET',
        success: result => {
          console.log("test", result)
          if (result.statusCode == 200) {
            this.patients = result.data
          }
          if (this.patients.length > 0) {
            this.selectedPatientId = this.patients[0].id;
            this.selectedPatientName = this.patients[0].name;
          }
        }
      })
    },
  },
  created() {
    this.getDoctorInfo()
    this.getPatients()
  }
};
</script>

<style scoped>
.page {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding-top: 20rpx;
}

.container {
  width: 100%;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
}

/* 🏥 医院信息样式 */
.hospital-info {
  display: flex;
  align-items: center;
}

.hospital-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
}

.hospital-details {
  display: flex;
  flex-direction: column;
}

.hospital-name {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
}

.hospital-department {
  font-size: 28rpx;
  color: #888;
}

/* 分割线 */
.divider {
  height: 2rpx;
  background-color: #f0f0f0;
  margin: 20rpx 0;
}

/* 👨‍⚕️ 医生信息样式 */
.doctor-info {
  padding: 10rpx 0;
}

.info-row {
  display: flex;
  margin-bottom: 10rpx;
}

.info-label {
  width: 140rpx;
  font-size: 28rpx;
  color: #666;
  font-weight: bold;
}

.doctor-speciality {
  padding-left: 140rpx;
  font-size: 26rpx;
  color: #555;
  line-height: 40rpx;
}

/* 🆕 就诊信息标题 */
.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

/* 选择就诊人行 */
.select-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.select-title {
  font-size: 28rpx;
  color: #555;
}

.manage-text {
  font-size: 28rpx;
  color: #007aff;
}

/* 就诊人列表 */
.patient-list {
  display: flex;
  flex-wrap: wrap;
}

.patient-item {
  display: flex;
  align-items: center;
  width: 45%;
  padding: 20rpx;
  margin: 10rpx 2.5%;
  background-color: #f5f5f5;
  border-radius: 12rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  border: 2rpx solid transparent;
}

.patient-item.selected {
  border-color: #4caf50;
}

.check-icon {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  border: 2rpx solid #ccc;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 20rpx;
}

.patient-item.selected .check-icon {
  border-color: #4caf50;
}

.patient-info {
  display: flex;
  flex-direction: column;
}

.patient-name {
  font-size: 28rpx;
  color: #333;
}

.patient-phone {
  font-size: 26rpx;
  color: #888;
}

/* 🆕 付款部分样式 */
.payment-section {
  margin-top: 30rpx;
}

.payment-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.payment-title {
  font-size: 30rpx;
  color: #333;
}

.payment-amount {
  font-size: 30rpx;
  color: #4caf50;
  font-weight: bold;
}

.refund-section {
  padding: 20rpx;
  background-color: #f9f9f9;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.refund-title {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.refund-rule {
  font-size: 26rpx;
  color: #666;
  line-height: 40rpx;
}

/* 立即预约按钮 */
.confirm-btn {
  width: 100%;
  padding: 20rpx;
  background-color: #007aff;
  color: #fff;
  font-size: 32rpx;
  border-radius: 12rpx;
}
</style>
